#!/bin/bash

# load config file
. /etc/archangel/archangel.conf > /dev/null 2>&1

PROG="archangel"
PROG_PATH="/usr/share/archangel"
PID_PATH="/var/run/"
BLOCKPAGE_PROC="blockpage"
BLOCKPAGE_IP=$blockpageip
BLOCKPAGE_PORT=$blockpageport
BLOCKPAGE_PATH="$blockpagedir"

start() {
    if [ -e "$PID_PATH/$PROG.pid" ]; then
        # Program is running, exit with error.
        echo "Error: $PROG is currently running!" 1>&2
        exit 1
    else
	python $PROG_PATH/$PROG.py >/dev/null 2>&1 &
        echo $! > "$PID_PATH/$PROG.pid"
        echo "$PROG started"
	if [ -e "$PID_PATH/$BLOCKPAGE_PROC.pid" ]; then
	    kill `cat $PID_PATH/$BLOCKPAGE_PROC.pid`
	    rm $PID_PATH/$BLOCKPAGE_PROC.pid
	fi
	php -S "$BLOCKPAGE_IP:$BLOCKPAGE_PORT" -t $BLOCKPAGE_PATH >/dev/null 2>&1 &
	echo $! > "$PID_PATH/$BLOCKPAGE_PROC.pid"
    fi
}

stop() {
    # Stop the block page
    if [ -e "$PID_PATH/$BLOCKPAGE_PROC.pid" ]; then
	kill `cat $PID_PATH/$BLOCKPAGE_PROC.pid`
	rm $PID_PATH/$BLOCKPAGE_PROC.pid
    fi

    if [ -e "$PID_PATH/$PROG.pid" ]; then
        # Program is running, so stop it
        kill `cat $PID_PATH/$PROG.pid`
        rm "$PID_PATH/$PROG.pid"
        echo "$PROG stopped"
    else
        # Program is not running, exit with error.
        echo "Error: $PROG not started!" 1>&2
        exit 1
    fi
}

# Check to see if we are running as root first.
if [ "$(id -u)" != "0" ]; then
    echo "This script must be run as root" 1>&2
    exit 1
fi

case "$1" in
    start)
        start
        exit 0
    ;;
    stop)
        stop
        exit 0
    ;;
    reload|restart|force-reload)
        stop
        start
        exit 0
    ;;
    **)
        echo "Usage: $0 {start|stop|reload}" 1>&2
        exit 1
    ;;
esac

